package com.yao.koin.bean

import com.yao.koin.util.Result
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope
import java.io.IOException

data class Banner<out T>(
    val data: List<BannerChild>,
    val status: Int
)

suspend fun <T : Any> Banner<T>.executeResponse(successBlock: (suspend CoroutineScope.() -> Unit)? = null,
                                                    errorBlock: (suspend CoroutineScope.() -> Unit)? = null): Result<List<BannerChild>> {
    return coroutineScope {
        if (status == 100 ) {
            successBlock?.let { it() }
            Result.Success(data)
        } else {
            errorBlock?.let { it() }
            Result.Error(IOException(status.toString()))
        }
    }
}


suspend fun <T : Any> Banner<T>.doSuccess(successBlock: (suspend CoroutineScope.(T) -> Unit)? = null): Banner<T> {
    return coroutineScope {
        if (status == 100 ) successBlock?.invoke(this, this@doSuccess.data)
        this@doSuccess
    }

}

private fun Any?.invoke(coroutineScope: CoroutineScope, data: List<BannerChild>) {

}


suspend fun <T : Any> Banner<T>.doError(errorBlock: (suspend CoroutineScope.(String) -> Unit)? = null): Banner<T> {
    return coroutineScope {
        if (status != 100 ) errorBlock?.invoke(this, this@doError.status.toString())
        this@doError
    }
}